﻿using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Xml;
//using System.Xml.XPath;
using System.Xml.Serialization;
using System.IO;

namespace VGS {
    public partial class Form1 : Form {
        private PlayerRadioButton[] radioButtonT1P;
        private PlayerRadioButton[] radioButtonT2P;
        private LogForm lf = new LogForm();

        #region Constructor
        public Form1()
        {
            InitializeComponent();
            toolStripLabelVersion.Text = string.Format("Version: {0}", AssemblyVersion);

            // Group the players together so we easy can loop throug them
            radioButtonT1P = new PlayerRadioButton[6] {
                prbT1P1,
                prbT1P2,
                prbT1P3,
                prbT1P4,
                prbT1P5,
                prbT1P6
            };
            radioButtonT2P = new PlayerRadioButton[6] {
                prbT2P1,
                prbT2P2,
                prbT2P3,
                prbT2P4,
                prbT2P5,
                prbT2P6
            };

            lf.Owner = this;

            // Get all added log messages so we can show them
            Log.Instance.MessageAdded += logMessageAdded;

            // ## EXPERIMENTAL
            VolleyMatch vm = VolleyMatch.Instance;
            vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerAdded += HomeTeam_LineupPlayerAdded;
            vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerRemoved += HomeTeam_LineupPlayerRemoved;
            vm.Sets.CurrentSet.Lineups.HomeTeam.PlayersRotated += new EventHandler(HomeTeam_LineupPlayersRotated);
            vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerAdded += AwayTeam_LineupPlayerAdded;
            vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerRemoved += AwayTeam_LineupPlayerRemoved;
            vm.Sets.CurrentSet.Lineups.AwayTeam.PlayersRotated += new EventHandler(AwayTeam_LineupPlayersRotated);

            vm.Sets.CurrentSet.SetReseted += new SetResetedEventHandler(CurrentSet_SetReseted);

            toolStripLabelSetCur.Text = "Current Set: " + vm.Sets.CurrentSet.Number;
            toolStripLabelSetTot.Text = "Total Sets: " + vm.Sets.Count;
            
            //vm.Sets.CurrentSet.StatusChanged += new StatusChanged(CurrentSet_StatusChanged);
        }
        #endregion

        /// <summary>
        /// Catches log message events and adds them to the log view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="msg"></param>
        private void logMessageAdded(object sender, LogMessageAddedEventArgs e)
        {
            // Add the log message to the listview on the log form
            lf.AddMessage(e.Message);
        }


        /// <summary>
        /// Gets the assembly's version
        /// </summary>
        private string AssemblyVersion {
            get {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }

        #region Custom methods
        private void SwitchSides()
        {
            Point tmp;

            // Switch team labels
            tmp = labelHomeTeam.Location;
            labelHomeTeam.Location = labelAwayTeam.Location;
            labelAwayTeam.Location = tmp;

            // Switch player list
            tmp = listViewHomeTeam.Location;
            listViewHomeTeam.Location = listViewAwayTeam.Location;
            listViewAwayTeam.Location = tmp;

            // Switch serve buttons
            tmp = labelHomeTeamServe.Location;
            labelHomeTeamServe.Location = labelAwayTeamServe.Location;
            labelAwayTeamServe.Location = tmp;

            tmp = prbHomeTeam.Location;
            prbHomeTeam.Location = prbAwayTeam.Location;
            prbAwayTeam.Location = tmp;

            tmp = prbT1P1.Location;
            prbT1P1.Location = prbT2P1.Location;
            prbT2P1.Location = tmp;

            tmp = prbT1P2.Location;
            prbT1P2.Location = prbT2P2.Location;
            prbT2P2.Location = tmp;

            tmp = prbT1P3.Location;
            prbT1P3.Location = prbT2P3.Location;
            prbT2P3.Location = tmp;

            tmp = prbT1P4.Location;
            prbT1P4.Location = prbT2P4.Location;
            prbT2P4.Location = tmp;

            tmp = prbT1P5.Location;
            prbT1P5.Location = prbT2P5.Location;
            prbT2P5.Location = tmp;

            tmp = prbT1P6.Location;
            prbT1P6.Location = prbT2P6.Location;
            prbT2P6.Location = tmp;
        }

        /// <summary>
        /// Unchecks all possible "scorers" (players or just the court)
        /// </summary>
        private void UncheckAllOnCourt() {
            prbHomeTeam.Checked = false;
            prbAwayTeam.Checked = false;

            for (int i = 0; i < 6; i++) {
                radioButtonT1P[i].Checked = false;
                radioButtonT2P[i].Checked = false;
            }
        }


        /// <summary>
        /// Updates the list of home players and adds them to the lineup picture
        /// </summary>
        private void UpdateHomeTeamPlayers()
        {
            VolleyMatch vm = VolleyMatch.Instance;

            for (int i = 0; i < 6; i++)
                radioButtonT1P[i].RemovePlayer();//.Text = string.Empty;

            listViewHomeTeam.Items.Clear();
            foreach (Player p in vm.HomeTeam.Players)
            {
                // See if the player is in the lineup and if so, which position
                //vm.Sets.CurrentSet.Lineups.HomeTeam.Exists(p);
                if (vm.Sets.CurrentSet.Lineups.HomeTeam.Exists(p))
                {
                    int pos = vm.Sets.CurrentSet.Lineups.HomeTeam.PositionOfPlayer(p) - 1;
                    radioButtonT1P[pos].SetPlayer(p);
                }
                else
                {
                    ListViewItem item = new ListViewItem(p.Shirt.ToString());
                    item.SubItems.Add(p.Name);
                    listViewHomeTeam.Items.Add(item);
                }
            }
        }


        /// <summary>
        /// Updates the list of away players and adds them to the lineup picture
        /// </summary>
        private void UpdateAwayTeamPlayers()
        {
            VolleyMatch vm = VolleyMatch.Instance;

            for (int i = 0; i < 6; i++)
                radioButtonT2P[i].RemovePlayer();//.Text = string.Empty;

            listViewAwayTeam.Items.Clear();
            foreach (Player p in vm.AwayTeam.Players)
            {
                // See if the player is in the lineup and if so, which position
                if (vm.Sets.CurrentSet.Lineups.AwayTeam.Exists(p))
                {
                    int pos = vm.Sets.CurrentSet.Lineups.AwayTeam.PositionOfPlayer(p) - 1;
                    radioButtonT2P[pos].SetPlayer(p);
                }
                else
                {
                    ListViewItem item = new ListViewItem(p.Shirt.ToString());
                    item.SubItems.Add(p.Name);
                    listViewAwayTeam.Items.Add(item);
                }
            }
        }


        /// <summary>
        /// Updates necessary info after a set has been changed
        /// </summary>
        private void UpdateSetInfo()
        {
            VolleyMatch vm = VolleyMatch.Instance;

            switch (vm.Sets.CurrentSet.Status)
            {
                case SetStatus.SET_WARMUP:
                    // enable and disable some buttons
                    //toolStripMenuItemStartSet.Enabled = true;
                    toolStripMenuItemEndSet.Enabled = false;
                    buttonScore.Enabled = false;
                    toolStripMenuItemStartSet.Enabled = true;
                    labelHomeTeamServe.Enabled = true;
                    labelAwayTeamServe.Enabled = true;
                    undoToolStripMenuItem.Enabled = false;

                    labelHomeTeamServe.BackColor = Color.FromKnownColor(KnownColor.Control);
                    labelAwayTeamServe.BackColor = Color.FromKnownColor(KnownColor.Control);

                    UpdateScore();

                    UpdateHomeTeamPlayers();
                    UpdateAwayTeamPlayers();
                    break;

                case SetStatus.SET_STARTED:
                    // Enable and disable some buttons
                    toolStripMenuItemStartSet.Enabled = false;
                    toolStripMenuItemEndSet.Enabled = true;
                    buttonScore.Enabled = true;
                    labelHomeTeamServe.Enabled = false;
                    labelAwayTeamServe.Enabled = false;

                    UpdateScore();

                    UpdateHomeTeamPlayers();
                    UpdateAwayTeamPlayers();

                    UpdateUndoScoreButton();
                    break;

                case SetStatus.SET_ENDED:
                    // Enable and disable some buttons
                    toolStripMenuItemStartSet.Enabled = false;
                    toolStripMenuItemEndSet.Enabled = false;
                    buttonScore.Enabled = false;
                    undoToolStripMenuItem.Enabled = false;
                    labelHomeTeamServe.Enabled = false;
                    labelAwayTeamServe.Enabled = false;

                    UpdateScore();

                    UpdateHomeTeamPlayers();
                    UpdateAwayTeamPlayers();
                    break;
            }

            labelHomeTeamSetWins.Text = vm.Sets.HomeTeamSetWins.ToString();
            labelAwayTeamSetWins.Text = vm.Sets.AwayTeamSetWins.ToString();

            //UpdateUndoScoreButton();
        }

        /// <summary>
        /// This method enables or disables the undo possibility
        /// </summary>
        private void UpdateUndoScoreButton()
        {
            VolleyMatch vm = VolleyMatch.Instance;

            if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
            {
                if (vm.Sets.CurrentSet.Points.Count > 0)
                    undoToolStripMenuItem.Enabled = true;
                else
                    undoToolStripMenuItem.Enabled = false;
            }
            else
            {
                //Console.WriteLine("UpdateUndoScoreButton: {0}", ex.Message);
                undoToolStripMenuItem.Enabled = false;
            }
        }

        /// <summary>
        /// Updates the score or sets it to "0 - 0" if the set hasn't started.
        /// This method is used when the user switches between sets by using the
        /// Next and Previous buttons. The score should otherwise be updated by
        /// registering to the sets ScoreChanged event.
        /// </summary>
        private void UpdateScore()
        {
            VolleyMatch vm = VolleyMatch.Instance;

            if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
            {
                labelScore.Text = vm.Sets.CurrentSet.Points.ToString();
                if (vm.Sets.CurrentSet.Points.HasServe == TeamEnum.HOME_TEAM)
                    SetHomeTeamServe();
                else
                    SetAwayTeamServe();
            }
            else
            {
                labelScore.Text = "0 - 0";
            }
        }
        #endregion

        #region "File" menu item events
        private void teamSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            DialogResult res = saveFileDialogTeam.ShowDialog();

            // Open the file for writing
            if (res == DialogResult.OK)
            {
                XmlSerializer xs = new XmlSerializer(typeof(Players));

                using (Stream s = saveFileDialogTeam.OpenFile())
                {
                    xs.Serialize(s, vm.HomeTeam.Players);
                }
                //System.IO.Stream file_handle = saveFileDialogTeam.OpenFile();

                //if (file_handle != null)
                //{
                //    byte[] buffer = new Byte[200];
                //    XmlSerializer xs = new XmlSerializer(typeof(Team));
                //    //System.IO.MemoryStream ms = new System.IO.MemoryStream();
                //    xs.Serialize(file_handle, vm.HomeTeam);
                //    file_handle.Close();
                //    //ms.Seek(0, 0);
                //    //NiceClass y;
                //    //y = (NiceClass)xs.Deserialize(ms);
                //    //ms.Seek(0, 0);
                //    //ms.Read(buffer, 0, 200);
                //    //string s = System.Text.Encoding.ASCII.GetString(buffer, 0, 200);
                //    //MessageBox.Show(Form.ActiveForm, s); // XML, here are you?

                //    /*
                //    XmlTextWriter writer = new XmlTextWriter(file_handle, Encoding.UTF8);

                //    writer.WriteStartDocument();
                //    writer.WriteComment("Volleyball Game Statistics Team file");

                //    writer.WriteStartElement("VGS");
                //    writer.WriteStartElement("Teams");
                    
                //    // Write home team
                //    writer.WriteStartElement("HomeTeam");
                    
                //    // Write the team's name as an attribute
                //    writer.WriteStartAttribute("name");
                //    writer.WriteString(vm.HomeTeam.Name);
                //    writer.WriteEndAttribute();

                //    // Add players to the home team
                //    writer.WriteStartElement("Players");
                //    foreach (Player p in vm.HomeTeam.Players) {
                //        writer.WriteStartElement("Player");
                //        writer.WriteStartAttribute("shirt");
                //        writer.WriteString(p.Shirt);
                //        writer.WriteEndAttribute();
                //        writer.WriteString(p.Name);
                //        writer.WriteEndElement(); // </Player>
                //    }
                //    writer.WriteEndElement(); // </Players>
                //    writer.WriteEndElement(); // </HomeTeam>

                //    // Write away team
                //    writer.WriteStartElement("AwayTeam");
                //    // Write the away team's name as an attribute
                //    writer.WriteStartAttribute("name");
                //    writer.WriteString(vm.AwayTeam.Name);
                //    writer.WriteEndAttribute();

                //    // Add players to the home team
                //    writer.WriteStartElement("Players");
                //    foreach (Player p in vm.AwayTeam.Players) {
                //        writer.WriteStartElement("Player");
                //        writer.WriteStartAttribute("shirt");
                //        writer.WriteString(p.Shirt);
                //        writer.WriteEndAttribute();
                //        writer.WriteString(p.Name);
                //        writer.WriteEndElement(); // </Player>
                //    }
                //    writer.WriteEndElement(); // </Players>
                //    writer.WriteEndElement(); // </AwayTeam>

                //    writer.WriteEndElement(); // </Teams>
                //    writer.WriteEndElement(); // </VGS>

                //    writer.WriteEndDocument();
                //    writer.Close();
                //    */
                //}
            }
        }

        private void teamSettingsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            DialogResult res = openFileDialogTeam.ShowDialog();

            if (res == DialogResult.OK)
            {
                System.IO.Stream handle = openFileDialogTeam.OpenFile();

                if (handle != null)
                {
                    //XPathNavigator nav;
                    //XPathDocument docNav = new XPathDocument(handle);
                    //XPathNodeIterator NodeIter;
                    //string strExpression;

                    //nav = docNav.CreateNavigator();
                    //strExpression = "//Teams";
                    //NodeIter = nav.Select(strExpression);

                    //// Go through the players
                    //while (NodeIter.MoveNext()) {
                    //      Console.WriteLine("Value: {0}", NodeIter.Current.Value);
                    //};




                    /*
                    XmlTextReader reader = new XmlTextReader(handle);
                    TeamEnum current = TeamEnum.TEAM_NONE;

                    while (reader.Read()) {
                        Console.WriteLine("DEBUG: {0}", reader.Name);
                        switch (reader.NodeType) {
                            case XmlNodeType.Element:
                                if (reader.Name == "HomeTeam") {
                                    current = TeamEnum.HOME_TEAM;
                                }
                                else if (reader.Name == "AwayTeam") {
                                    current = TeamEnum.AWAY_TEAM;
                                }
                                break;
                            case XmlNodeType.Attribute:
                                if (current == TeamEnum.HOME_TEAM) {
                                    Console.WriteLine("HomeTeam: {0}", reader.Name);
                                }
                                else if (current == TeamEnum.AWAY_TEAM) {
                                    Console.WriteLine("AwayTeam: {0}", reader.Name);
                                }
                                break;
                            case XmlNodeType.Text:
                                break;
                        }
                    }

                    reader.Close();
                    handle.Close();
                    */

                    //handle.Close();
                }
            }
        }
        
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region "Help" menu items events
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }
        #endregion

        #region "Sets" menu items events
        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;

            vm.Sets.CurrentSet.Reset();
        }

        private void ToolStripMenuItemPrevSet_Click(object sender, EventArgs e) {
            VolleyMatch vm = VolleyMatch.Instance;

            

            // Changes the CurrentSet indexer to the previous set if possible
            if (vm.Sets.Previous())
            {
                // Add the events for this new 'current set'
                vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerAdded += HomeTeam_LineupPlayerAdded;
                vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerRemoved += HomeTeam_LineupPlayerRemoved;
                vm.Sets.CurrentSet.Lineups.HomeTeam.PlayersRotated += HomeTeam_LineupPlayersRotated;
                vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerAdded += AwayTeam_LineupPlayerAdded;
                vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerRemoved += AwayTeam_LineupPlayerRemoved;
                vm.Sets.CurrentSet.Lineups.AwayTeam.PlayersRotated += AwayTeam_LineupPlayersRotated;
                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                    vm.Sets.CurrentSet.Points.ScoreChanged += Points_ScoreChanged;
                vm.Sets.CurrentSet.SetReseted += new SetResetedEventHandler(CurrentSet_SetReseted);

                if (vm.Sets.CurrentSet.Number <= 1)
                {
                    toolStripMenuItemPrevSet.Enabled = false;
                }
                if (vm.Sets.CurrentSet.Number < vm.Sets.Count)
                {
                    toolStripMenuItemNextSet.Enabled = true;
                }
                if (vm.Sets.CurrentSet.Number > 1)
                {
                    toolStripMenuItemPrevSet.Enabled = true;
                }

                toolStripLabelSetCur.Text = "Current Set: " + vm.Sets.CurrentSet.Number;
                UpdateSetInfo();
            }
        }

        private void ToolStripMenuItemNextSet_Click(object sender, EventArgs e) {
            VolleyMatch vm = VolleyMatch.Instance;

            //// Remove all associated events for the current set
            //vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerAdded = null;
            //vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerRemoved = null;
            //vm.Sets.CurrentSet.Lineups.HomeTeam.PlayersRotated = null;
            //vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerAdded = null;
            //vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerRemoved = null;
            //vm.Sets.CurrentSet.Lineups.AwayTeam.PlayersRotated = null;
            //if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
            //    vm.Sets.CurrentSet.Points.ScoreChanged = null;
            //vm.Sets.CurrentSet.SetReseted = null;

            if (vm.Sets.Next())
            {
                // Add the events for this new 'current set'
                vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerAdded += HomeTeam_LineupPlayerAdded;
                vm.Sets.CurrentSet.Lineups.HomeTeam.PlayerRemoved += HomeTeam_LineupPlayerRemoved;
                vm.Sets.CurrentSet.Lineups.HomeTeam.PlayersRotated += HomeTeam_LineupPlayersRotated;
                vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerAdded += AwayTeam_LineupPlayerAdded;
                vm.Sets.CurrentSet.Lineups.AwayTeam.PlayerRemoved += AwayTeam_LineupPlayerRemoved;
                vm.Sets.CurrentSet.Lineups.AwayTeam.PlayersRotated += AwayTeam_LineupPlayersRotated;
                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                    vm.Sets.CurrentSet.Points.ScoreChanged += Points_ScoreChanged;
                vm.Sets.CurrentSet.SetReseted += new SetResetedEventHandler(CurrentSet_SetReseted);

                if (vm.Sets.CurrentSet.Number == vm.Sets.Count)
                {
                    toolStripMenuItemNextSet.Enabled = false;
                }
                if (vm.Sets.CurrentSet.Number < vm.Sets.Count)
                {
                    toolStripMenuItemNextSet.Enabled = true;
                }
                if (vm.Sets.CurrentSet.Number > 1)
                {
                    toolStripMenuItemPrevSet.Enabled = true;
                }

                toolStripLabelSetCur.Text = "Current Set: " + vm.Sets.CurrentSet.Number;
                UpdateSetInfo();
            }
        }

        private void ToolStripMenuItemNewSet_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            vm.Sets.Add(new Set(vm.Sets.Count+1));

            // Check whether or not to enable the Previous set button
            if (vm.Sets.CurrentSet.Number > 1)
                toolStripMenuItemPrevSet.Enabled = true;
            else
                toolStripMenuItemPrevSet.Enabled = false;

            // Check whether or not to enable the next set button
            if (vm.Sets.CurrentSet.Number == vm.Sets.Count)
                toolStripMenuItemNextSet.Enabled = false;
            else
                toolStripMenuItemNextSet.Enabled = true;

            toolStripLabelSetTot.Text = "Total Sets: " + vm.Sets.Count;

            //UpdateSetInfo();
        }

        private void toolStripMenuItemStartSet_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;

            if (vm.Sets.CurrentSet.Status == SetStatus.SET_STARTED)
            {
                MessageBox.Show("This set has already started", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (vm.Sets.CurrentSet.Status == SetStatus.SET_ENDED)
            {
                MessageBox.Show("This set has ended", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // The set is in SET_WARMUP

            // Make sure the lineups are full
            if (!vm.Sets.CurrentSet.Lineups.AreFull)
            {
                MessageBox.Show("Must fill the team's lineups first!", "Information",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                //log.AddMessage("Both team's lineups must be filled before the game can start");
                return;
            }              

            // Make sure the serving team is selected
            if (labelHomeTeamServe.BackColor != Color.LightGreen && labelAwayTeamServe.BackColor != Color.LightGreen)
            {
                MessageBox.Show("Select team that starts serving", "Information",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Everything is fine--start the set!
            if (labelHomeTeamServe.BackColor == Color.LightGreen) {
                vm.Sets.CurrentSet.Start(TeamEnum.HOME_TEAM);
            }
            else {
                vm.Sets.CurrentSet.Start(TeamEnum.AWAY_TEAM);
            }

            // Add event
            vm.Sets.CurrentSet.Points.ScoreChanged += Points_ScoreChanged;
            labelScore.Text = vm.Sets.CurrentSet.Points.ToString();

            //timerSetLength.Start();

            buttonScore.Enabled = true;
            toolStripMenuItemStartSet.Enabled = false;
            toolStripMenuItemEndSet.Enabled = true;
            labelHomeTeamServe.Enabled = false;
            labelAwayTeamServe.Enabled = false;

            //UpdateCourtRotations();
          }

        private void toolStripMenuItemEndSet_Click(object sender, EventArgs e) {
            VolleyMatch vm = VolleyMatch.Instance;

            vm.Sets.CurrentSet.End();
            //timerSetLength.Stop();

            toolStripMenuItemEndSet.Enabled = false;
            buttonScore.Enabled = false;

            labelHomeTeamSetWins.Text = vm.Sets.HomeTeamSetWins.ToString();
            labelAwayTeamSetWins.Text = vm.Sets.AwayTeamSetWins.ToString();
        }
        #endregion

        #region "Edit" menu items events
        private void teamsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TeamSettingsForm t = new TeamSettingsForm();
            t.ShowDialog(this);

            // After the team settings dialog has closed some info needs to be
            // updated in the main window

            VolleyMatch vm = VolleyMatch.Instance;

            labelHomeTeam.Text = vm.HomeTeam.Name;
            labelAwayTeam.Text = vm.AwayTeam.Name;

            toolTip1.SetToolTip(labelScore, vm.HomeTeam.Name + " - " + vm.AwayTeam.Name);

            UpdateSetInfo();
        }

        private void viewLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!lf.Visible)
            {
                //if (lf.Docked)
                //{
                    //Point p = new Point(this.Location.X, this.Bottom);

                    //lf.Location = p; // lf's StartPosition is set to Manual
                    lf.Show(this);
                    
                //}
                //else lf.Show(this);
            }
        }

        private void viewStatisticsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StatisticsForm stats = new StatisticsForm();
            stats.ShowDialog();
            stats.Close();
        }
        #endregion

        #region Serve label methods
        /// <summary>
        /// Makes the home team's serve label green and the away team's
        /// control colored.
        /// </summary>
        private void SetHomeTeamServe() {
            labelAwayTeamServe.BackColor = Color.FromKnownColor(KnownColor.Control);
            labelHomeTeamServe.BackColor = Color.LightGreen;
        }

        /// <summary>
        /// Makes the away team's serve label green and the home team's
        /// control colored.
        /// </summary>
        private void SetAwayTeamServe() {
            labelHomeTeamServe.BackColor = Color.FromKnownColor(KnownColor.Control);
            labelAwayTeamServe.BackColor = Color.LightGreen;
        }
        
        /// <summary>
        /// Selects home team as the serving team
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Click EventArgs</param>
        private void labelHomeTeamServe_Click(object sender, EventArgs e) {
            SetHomeTeamServe();
        }

        /// <summary>
        /// Selects away team as the serving team
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Click EventArgs</param>
        private void labelAwayTeamServe_Click(object sender, EventArgs e) {
            SetAwayTeamServe();
        }
        #endregion

        #region Home Team double click and drag over/drop
        private void listViewHomeTeam_DoubleClick(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            ListView.SelectedListViewItemCollection items = ((ListView)sender).SelectedItems;

            Player p = vm.HomeTeam.Players[items[0].Text];

            if (p != null)
            {
                for (int i = 0; i < 6; i++)
                {
                    // When we find an unused position
                    if (!radioButtonT1P[i].HasPlayer)
                    {
                        vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, i + 1);

                        // Last, we need to remove the item from the ListView
                        ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                        ic.Remove(items[0]);
                        break;
                    }
                }
            }
        }

        private void listViewHomeTeam_ItemDrag(object sender, ItemDragEventArgs e) {
            VolleyMatch vm = VolleyMatch.Instance;

            try {
                Set s = vm.Sets.CurrentSet;
                listViewHomeTeam.DoDragDrop(e.Item, DragDropEffects.Move);
            }
            catch (Exception) { }
        }

        private void prbT1P1_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewHomeTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT1P1_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;
            
            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT1P1.HasPlayer) {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT1P1.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.HomeTeam.Remove(1);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing home team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.HomeTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, 1); // event will add text on the screen

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.HomeTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping player: {0}", ex.Message);
            }
        }

        private void prbT1P2_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewHomeTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT1P2_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT1P2.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT1P2.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.HomeTeam.Remove(2);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing home team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.HomeTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, 2);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.HomeTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping player: {0}", ex.Message);
            }
        }

        private void prbT1P3_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewHomeTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT1P3_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT1P3.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT1P3.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.HomeTeam.Remove(3);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing home team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.HomeTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, 3);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.HomeTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping player: {0}", ex.Message);
            }
        }

        private void prbT1P4_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewHomeTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT1P4_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT1P4.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT1P4.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.HomeTeam.Remove(4);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing home team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.HomeTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, 4);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.HomeTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping player: {0}", ex.Message);
            }
        }

        private void prbT1P5_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewHomeTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT1P5_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT1P5.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT1P5.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.HomeTeam.Remove(5);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing home team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.HomeTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, 5);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.HomeTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping player: {0}", ex.Message);
            }
        }

        private void prbT1P6_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewHomeTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT1P6_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT1P6.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT1P6.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.HomeTeam.Remove(6);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing home team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.HomeTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.HomeTeam.Add(p, 6);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewHomeTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.HomeTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping player: {0}", ex.Message);
            }
        }
        #endregion

        #region Away Team double click and drag over/drop
        private void listViewAwayTeam_DoubleClick(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            ListView.SelectedListViewItemCollection items = ((ListView)sender).SelectedItems;

            Player p = vm.AwayTeam.Players[items[0].Text];

            if (p != null)
            {
                for (int i = 0; i < 6; i++)
                {
                    // When we find an unused position
                    if (!radioButtonT2P[i].HasPlayer)
                    {
                        vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, i + 1);

                        // Last, we need to remove the item from the ListView
                        ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                        ic.Remove(items[0]);
                        break;
                    }
                }
            }
        }

        private void listViewAwayTeam_ItemDrag(object sender, ItemDragEventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;

            Set s = vm.Sets.CurrentSet;
            listViewAwayTeam.DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void prbT2P1_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewAwayTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT2P1_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT2P1.HasPlayer) {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT2P1.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.AwayTeam.Remove(1);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing away team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.AwayTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, 1);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.AwayTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping away team player: {0}", ex.Message);
            }
        }

        private void prbT2P2_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewAwayTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT2P2_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT2P2.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT2P2.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.AwayTeam.Remove(2);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing away team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.AwayTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, 2);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.AwayTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping away team player: {0}", ex.Message);
            }
        }

        private void prbT2P3_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewAwayTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT2P3_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT2P3.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT2P3.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.AwayTeam.Remove(3);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing away team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.AwayTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, 3);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.AwayTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping away team player: {0}", ex.Message);
            }
        }

        private void prbT2P4_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewAwayTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT2P4_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT2P4.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT2P4.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.AwayTeam.Remove(4);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing away team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.AwayTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, 4);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.AwayTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping away team player: {0}", ex.Message);
            }
        }

        private void prbT2P5_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewAwayTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT2P5_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT2P5.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT2P5.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.AwayTeam.Remove(5);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing away team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.AwayTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, 5);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.AwayTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping away team player: {0}", ex.Message);
            }
        }

        private void prbT2P6_DragOver(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(typeof(ListViewItem))) {
                ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (item.ListView.Name == "listViewAwayTeam")
                    e.Effect = DragDropEffects.Move;
            }
            else e.Effect = DragDropEffects.None;
        }

        private void prbT2P6_DragDrop(object sender, DragEventArgs e) {
            if (!e.Data.GetDataPresent(typeof(ListViewItem))) return;

            VolleyMatch vm = VolleyMatch.Instance;
            Player substitute = null;

            // If a player already is at this position we must remove it and
            // readd it to the player list
            if (prbT2P6.HasPlayer)
            {
                try {
                    if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP)
                        substitute = prbT2P6.GetPlayer();
                    vm.Sets.CurrentSet.Lineups.AwayTeam.Remove(6);
                }
                catch (Exception ex) {
                    Console.WriteLine("Exception when removing away team player from lineup: {0}", ex.Message);
                }
            }

            ListViewItem item = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

            try {
                Player p = vm.AwayTeam.Players[item.Text];
                vm.Sets.CurrentSet.Lineups.AwayTeam.Add(p, 6);

                // Remove that item so it can't be used again
                ListView.ListViewItemCollection ic = listViewAwayTeam.Items;
                ic.Remove(item);

                if (vm.Sets.CurrentSet.Status != SetStatus.SET_WARMUP && substitute != null)
                    Log.Instance.AddMessage(string.Format("{0}'s {1} ({2}) was substituted with {3} ({4})",
                        vm.AwayTeam.Name, substitute.Name, substitute.Shirt, p.Name, p.Shirt));
            }
            catch (Exception ex) {
                Console.WriteLine("Exception when dropping away team player: {0}", ex.Message);
            }
        }
        #endregion        

        #region Form Behaviour
        private void Form1_LocationChanged(object sender, EventArgs e)
        {
            if (lf.Docked)
            {
                Point p = new Point(this.Location.X, this.Bottom);

                lf.Location = p;
            }
        }
        #endregion

        #region Set Events
        /// <summary>
        /// This method catches events occured when the set score is changed and updates
        /// components accordingly.
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">ScoreChangedEventArgs</param>
        private void Points_ScoreChanged(object sender, ScoreChangedEventArgs e) {
            Set current = sender as Set;
            labelScore.Text = e.Score;

            if (e.TotalPoints > 0) {
                undoToolStripMenuItem.Enabled = true;
            }
            else {
                undoToolStripMenuItem.Enabled = false;
            }

            // Change the green serving "icon"
            if (e.Team == TeamEnum.HOME_TEAM)
            {
                labelHomeTeamServe.BackColor = Color.LightGreen;
                labelAwayTeamServe.BackColor = Color.FromKnownColor(KnownColor.Control);
            }
            else if (e.Team == TeamEnum.AWAY_TEAM)
            {
                labelHomeTeamServe.BackColor = Color.FromKnownColor(KnownColor.Control);
                labelAwayTeamServe.BackColor = Color.LightGreen;
            }
        }

        /// <summary>
        /// Method run when the SetReseted event occurs. This method resets set information.
        /// For a fully successful reset, one should listen to the lineup player removed events,
        /// so that the persons in the lineup are moved back to the players list.
        /// </summary>
        /// <param name="sender">The current set</param>
        private void CurrentSet_SetReseted(object sender)
        {
            labelScore.Text = "0 - 0";
            buttonScore.Enabled = false;
            undoToolStripMenuItem.Enabled = false;
        }
        #endregion

        #region Home Team Events
        private void HomeTeam_LineupPlayerAdded(object sender, LineupEventArgs e)
        {
            radioButtonT1P[e.Position - 1].SetPlayer(e.Player);
        }

        private void HomeTeam_LineupPlayerRemoved(object sender, LineupEventArgs e)
        {
            radioButtonT1P[e.Position - 1].RemovePlayer();

            // Re-add player to player list
            ListViewItem item = new ListViewItem(e.Player.Shirt);
            item.SubItems.Add(e.Player.Name);
            listViewHomeTeam.Items.Add(item);
        }

        private void HomeTeam_LineupPlayersRotated(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            for (int i = 0; i < 6; i++)
            {
                radioButtonT1P[i].SetPlayer(vm.Sets.CurrentSet.Lineups.HomeTeam[i+1]);
            }
        }
        #endregion

        #region Away Team Events
        private void AwayTeam_LineupPlayerAdded(object sender, LineupEventArgs e)
        {
            if (e.Player != null)
            {
                radioButtonT2P[e.Position - 1].SetPlayer(e.Player);
            }
            else
            {
                MessageBox.Show("Player == null", "AwayTeam_LineupPlayerAdded", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AwayTeam_LineupPlayerRemoved(object sender, LineupEventArgs e)
        {
            radioButtonT2P[e.Position - 1].RemovePlayer();

            // Re-add player to player list
            ListViewItem item = new ListViewItem(e.Player.Shirt);
            item.SubItems.Add(e.Player.Name);
            listViewAwayTeam.Items.Add(item);
        }

        private void AwayTeam_LineupPlayersRotated(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;
            for (int i = 0; i < 6; i++)
            {
                radioButtonT2P[i].SetPlayer(vm.Sets.CurrentSet.Lineups.AwayTeam[i+1]);
            }
        }
        #endregion

        #region Scoring / undo score
        private void buttonScore_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;

            // Make sure the set has started, otherwise one should not be
            // able to score! If the set is started, then CurrentSet.Points
            // won't cause an exception
            if (vm.Sets.CurrentSet.Status != SetStatus.SET_STARTED)
            {
                buttonScore.Enabled = false;
                return;
            }

            // ##### NOTE #####
            // radioButtonT1P[] and players[] are related by their indexes
            // radioButtonT1P[1] == home_team_lineup[1] 

            // Home team scored
            if (prbHomeTeam.Checked)
            {
                prbHomeTeam.Checked = false;
                vm.Sets.CurrentSet.Points.Add(new SetPoint(TeamEnum.HOME_TEAM));
                return;
            }

            // Away team scored
            if (prbAwayTeam.Checked)
            {
                prbAwayTeam.Checked = false;
                vm.Sets.CurrentSet.Points.Add(new SetPoint(TeamEnum.AWAY_TEAM));
                return;
            }

            // A specific player scored
            for (int i = 0; i < 6; i++)
            {
                // Checking home team
                if (radioButtonT1P[i].Checked)
                {
                    radioButtonT1P[i].Checked = false; // to make sure there is no unintentional double click for example.

                    if (vm.HomeTeam.Players.Exists(pl => pl.Shirt == radioButtonT1P[i].Text))
                    {
                        Player p = vm.HomeTeam.Players[radioButtonT1P[i].Text];

                        // Get the type of point
                        PointType? type;
                        // Check if the one who served scored
                        if (i == 0 && vm.Sets.CurrentSet.Points.HasServe == TeamEnum.HOME_TEAM)
                            type = new TypeOfPointForm(true).GetPointType();
                        else type = new TypeOfPointForm(false).GetPointType();

                        // If it is UNKNOWN, then the user probably isn't sure, and maybe wanted
                        // to abort
                        if (type == null) return;

                        SetPoint point = new SetPoint(TeamEnum.HOME_TEAM, p, type);
                        vm.Sets.CurrentSet.Points.Add(point);
                    }
                    else
                        MessageBox.Show("Radiobuttons and lineup out of sync", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }

                // Checking away team
                if (radioButtonT2P[i].Checked)
                {
                    radioButtonT2P[i].Checked = false;

                    if (vm.AwayTeam.Players.Exists(pl => pl.Shirt == radioButtonT2P[i].Text))
                    {
                        //radioButtonT2P[i].Text = "hej";
                        Player p = vm.AwayTeam.Players[radioButtonT2P[i].Text];

                        // Get the type of point
                        PointType? type;
                        if (i == 0 && vm.Sets.CurrentSet.Points.HasServe == TeamEnum.AWAY_TEAM)
                            type = new TypeOfPointForm(true).GetPointType();
                        else type = new TypeOfPointForm(false).GetPointType();

                        // If it is null, then the user probably's not sure, and maybe wanted
                        // to abort
                        if (type == null) return;

                        SetPoint point = new SetPoint(TeamEnum.AWAY_TEAM, p, type);
                        vm.Sets.CurrentSet.Points.Add(point);
                    }
                    else
                        MessageBox.Show("Radiobuttons and lineup out of sync", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }
        }

        private void undoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            VolleyMatch vm = VolleyMatch.Instance;

            SetPoints points;
            try
            {
                points = vm.Sets.CurrentSet.Points;
                points.Undo();
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Console.WriteLine("Undo point: {0}", ex.Message);
            }
        }
        #endregion

        private void switchSidesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SwitchSides();
        }
    }
}
